import random

import cv2
import numpy as np

def salt_pepper_noise(image,ratio):
    out=np.zeros(image.shape,np.uint8)
    thres=1-ratio
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn=np.random.random()
            # rdn=random.Random()
            if rdn<ratio:
                out[i][j]=0
            elif rdn>thres:
                out[i][j]=255
            else:
                out[i][j]=image[i][j]
    return out

img=cv2.imread(r'CV-Pictures/036.jpg')
cv2.imshow('img',img)
out_sp_noise=salt_pepper_noise(img,0.2)
# dst_blur=cv2.blur(out_sp_noise,(9,9))
# dst=cv2.GaussianBlur(out_sp_noise,(9,9),2,2)
dst=cv2.medianBlur(out_sp_noise,5)
cv2.imshow('out_sp_noise',out_sp_noise)
cv2.imshow('dst_media_blur',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
